package com.im.service.job;

import cn.hutool.core.text.StrPool;
import cn.hutool.json.JSONUtil;
import com.im.service.domain.entity.ImChat;
import com.im.service.domain.entity.ImUser;
import com.im.service.mapper.ImChatMapper;
import com.im.service.mapper.ImUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

import static com.im.service.service.impl.ImChatServiceImpl.userChat;

/**
 * 同步会话
 *
 * @author liuzhiqiang
 */
@Component
public class SyncUserCache {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ImUserMapper userMapper;

    @Autowired
    private ImChatMapper chatMapper;

    @Scheduled(cron = "0 0 23 * * ?")
    public void syncUserCache() {
        List<ImUser> userList = userMapper.selectList(null);
        HashOperations<String, String, String> hashOperations = redisTemplate.opsForHash();
        for (ImUser imUser : userList) {
            List<String> imChatList = hashOperations.values(userChat + StrPool.COLON + imUser.getId());
            for (String str : imChatList) {
                ImChat imChat = JSONUtil.toBean(str, ImChat.class);
                chatMapper.updateById(imChat);
            }
        }
    }
}
